package model

import (
	"awesomeProject2/global"
	"awesomeProject2/utils"
	"gorm.io/gorm"
	"strconv"
	"strings"
)

type Paper struct {
	gorm.Model
	MagazineName  string `json:"magazineName" gorm:"type:varchar(255)"`
	PaperName     string `json:"paperName"  gorm:"type:varchar(255);index:paper_unique, unique"`
	PaperFile     string `json:"paperFile" gorm:"type:varchar(255)"`
	PaperCategory string `json:"paperCategory"  gorm:"type:varchar(255)"`
	PaperLevels   string `json:"paperLevel" gorm:"type:varchar(255)"`
	PaperRole     string `json:"paperRole" gorm:"type:varchar(255)"`
	UserId        uint   `json:"userid" gorm:"type:bigint;index:paper_unique, unique"`
	PaperAuthors  string `json:"paperAuthors"  gorm:"type:varchar(255);"`
	IsVisible     bool   `json:"is_visible" gorm:"type:tinyint"`
	Year          int    `json:"year" gorm:"type:int;"`
	InvalidFlag   int    `json:"invalidFlag" gorm:"comment:论文计分失效标志，默认为0,计分有效;type:tinyint;default: 0"`
}
type Level struct {
	gorm.Model
	Name string `json:"magazineName" gorm:"type:varchar(255)"`
}
type PaperToLevel struct {
	PaperId uint `json:"paper_id" gorm:"primary_key"`
	LevelId uint `json:"level_id" gorm:"primary_key"`
	Year    int  `json:"year"`
	UserId  uint `json:"user_id"`
}

func GetPaperIdsByLevelId(levelId string) (paperIds []uint, err error) {
	var papers []PaperToLevel
	err = global.GVA_DB.Where("level_id = ?", levelId).Select("paper_id").Find(&papers).Error
	for _, row := range papers {
		paperIds = append(paperIds, row.PaperId)
	}
	return paperIds, err
}

func GetPaper(id uint) (err error, paper Paper) {
	err = global.GVA_DB.Where("id = ?", id).First(&paper).Error
	return err, paper
}

func CreatePaper(paper *Paper) (err error) {
	//事务
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		// 在事务中执行一些 db 操作（从这里开始，您应该使用 'tx' 而不是 'db'）
		if err := tx.Create(&paper).Error; err != nil {
			// 返回任何错误都会回滚事务
			return err
		}
		arr := strings.Split(paper.PaperLevels, ",")
		intArr := utils.StringList2Int(arr)
		for _, level := range intArr {
			var data PaperToLevel
			//Year := GetYear()
			data = PaperToLevel{LevelId: uint(level), PaperId: paper.ID, Year: paper.Year, UserId: paper.UserId}
			if err := tx.Create(&data).Error; err != nil {
				return err
			}
		}
		// 返回 nil 提交事务
		return nil
	})
	return err
}

func DeletePaper(id int) (err error) {
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		// 在事务中执行一些 db 操作（从这里开始，您应该使用 'tx' 而不是 'db'）
		if err := tx.Where("id = ?", id).Unscoped().Delete(&Paper{}).Error; err != nil {
			// 返回任何错误都会回滚事务
			return err
		}
		//删除关系表
		if err := tx.Where("paper_id = ?", id).Unscoped().Delete(&PaperToLevel{}).Error; err != nil {
			return err
		}
		// 返回 nil 提交事务
		return nil
	})
	return err
}

func UpdatePaper(paper Paper) (err error) {
	err = global.GVA_DB.Transaction(func(tx *gorm.DB) error {
		// 在事务中执行一些 db 操作（从这里开始，您应该使用 'tx' 而不是 'db'）
		if err := tx.Where("id = ?", paper.ID).Updates(&paper).Error; err != nil {
			// 返回任何错误都会回滚事务
			return err
		}
		//删除关系表
		if err := tx.Where("paper_id = ?", paper.ID).Delete(&PaperToLevel{}).Error; err != nil {
			return err
		}
		arr := strings.Split(paper.PaperLevels, ",")
		intarr := utils.StringList2Int(arr)
		for _, level := range intarr {
			var data PaperToLevel
			//Year := GetYear()
			data = PaperToLevel{LevelId: uint(level), PaperId: paper.ID, Year: paper.Year, UserId: paper.UserId}
			if err := tx.Create(&data).Error; err != nil {
				return err
			}
		}
		// 返回 nil 提交事务
		return nil
	})
	return err
}

func GetPapers(userid uint, pageSize int, pageNum int) (err error, list interface{}, total int) {
	var papers []Paper
	var tt int64
	err = global.GVA_DB.Limit(pageSize).Offset((pageNum-1)*pageSize).Preload("PaperLevel").Where("user_id = ?", userid).Find(&papers).Count(&tt).Error

	tmp := strconv.FormatInt(tt, 10)
	total, _ = strconv.Atoi(tmp)
	return err, papers, total
}

func ChangePaperVisiblity(id uint) (err error) {
	var data Paper
	global.GVA_DB.Where("id = ?", id).First(&data)
	err = global.GVA_DB.Model(&Paper{}).Where("id = ?", id).Update("is_visible", !data.IsVisible).Error
	return err
}

func GetAllPapers(id uint, year int) (error, interface{}, int64) {
	var data []Paper
	var tt int64
	err := global.GVA_DB.Where("user_id = ? AND year = ?", id, year).Find(&data).Count(&tt).Error
	return err, data, tt
}
func GetAllPapers3(id uint) (error, interface{}, int64) {
	var data []Paper
	var tt int64
	//Year := GetYear()
	err := global.GVA_DB.Where("user_id = ? ", id).Find(&data).Count(&tt).Error
	return err, data, tt
}

// GetAllpp 统计总数目
func GetAllpp(year int) (error, int64) {
	var tt int64
	err := global.GVA_DB.Model(&Paper{}).Where("year = ?", year).Count(&tt).Error
	return err, tt
}

//统计paper明细
